﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseData.UI;

namespace Admin.Tax
{
    public partial class Recovery : BaseCommon.BasePage
    {
        protected static object locker = new object();
        protected string dbName = PageContext.GetConfig("DbName");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HasPower())
            {
                Jscript.AlertAndGoBack("您权限不足，不能操作");
                return;
            }
            string action = PageContext.GetRequest("action");
            if (!string.IsNullOrEmpty(action))
            {
                lock (locker)
                {
                    RecoveryDB();
                }
            }
        }

        protected void RecoveryDB()
        {
            bool isSuccess = true;
            string message = string.Empty;
            string filePath = PageContext.GetConfig("FilePath") + "Recovery\\LNHouse" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bak";
            try
            {
                //文件夹不存在即创建
                FileInfo fi = new FileInfo(filePath);
                if (!System.IO.Directory.Exists(fi.Directory.FullName))
                {
                    System.IO.Directory.CreateDirectory(fi.Directory.FullName);
                }
                HttpPostedFile fileDB = Request.Files["fUpFile"];
                if (fileDB != null && fileDB.FileName.EndsWith("bak", StringComparison.CurrentCultureIgnoreCase))
                {
                    fileDB.SaveAs(filePath);
                    isSuccess = BaseData.DataConfig.Recovery(BaseData.BusinessType.DBAdmin, filePath, dbName);
                    if (isSuccess)
                    {
                        //string sqlFilePath = Server.MapPath("..\\Config\\InitLoginUser.sql");
                        //string sql = BaseData.Common.FileHelper.GetContent(sqlFilePath);
                        //sql = sql.Replace("\r\n", "\n");
                        //sql = sql.Replace("GO", "\n");
                        //BaseData.DataConfig.QueryRecords(BaseData.BusinessType.DBAdmin, sql);
                    }
                }
                else
                {
                    Jscript.AlertAndRedirect("请选择要还原的数据库文件", "Recovery.aspx");
                    return;
                }
            }
            catch (Exception e)
            {
                isSuccess = false;
                message = "还原数据库出错，出错信息" + e.Message;
            }
            if (isSuccess)
            {
                Jscript.AlertAndRedirect("还原成功", "Recovery.aspx");
                return;
            }
            else
            {
                Jscript.AlertAndRedirect(message, "Recovery.aspx");
                return;
            }
        }
    }
}